<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名称" prop="name" maxlength="20">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入客户名称"
          clearable
          maxlength="20"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户电话" prop="phone" maxlength="11">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入客户电话"
          clearable
          oninput="value=value.replace(/\D/g,'')"
          maxlength="11"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户地址" prop="customerAddress">
        <el-cascader
          style="width: 100%"
          expand-trigger="hover"
          ref="cascaderAddr"
          size="small"
          :options="options"
          v-model="querySelectedOptions"
          @change="handleChange1"
          @keyup.enter.native="handleQuery"
        >
          <template slot-scope="{ node, data }">
            <span>{{ data.label }}</span>
            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
          </template>
        </el-cascader>
      </el-form-item>
      <el-form-item label="客户等级" prop="customerCategory">
        <el-select v-model="queryParams.customerCategory" placeholder="请选择客户等级" clearable>
          <el-option
            v-for="dict in dict.type.customer_grade"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['erp:customer:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['erp:customer:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['erp:customer:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :close-on-click-modal = "false" :data="customerList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center">
        <template slot-scope="scope">
          <span>{{ (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="客户名称" align="center" prop="name"/>
      <el-table-column label="客户电话" align="center" prop="phone"/>
      <el-table-column label="客户地址" align="center" prop="customerAddress"/>
      <el-table-column label="详细地址" align="center" prop="detailedAddress"/>
      <el-table-column label="客户等级" align="center" prop="customerCategory">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.customer_grade" :value="scope.row.customerCategory"/>
        </template>
      </el-table-column>
      <el-table-column label="客户开户银行" align="center" prop="customerBank"/>
      <el-table-column label="客户银行卡号" align="center" prop="customerBankAccount"/>
      <el-table-column label="备注信息" align="center" prop="remarks" show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['erp:customer:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['erp:customer:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改客户管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" :close-on-click-modal = "false"  append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入客户名称" maxlength="20"/>
        </el-form-item>
        <el-form-item label="客户电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入客户电话" maxlength="11" @input="v => form.phone = v.replace(/[^\d]/g,'')"/>
        </el-form-item>
        <el-form-item label="客户地址" prop="customerAddress">
          <el-cascader
            style="width: 100%"
            expand-trigger="hover"
            ref="cascaderAddr"
            size="small"
            :options="options"
            v-model="selectedOptions"
            @change="handleChange">
            <template slot-scope="{ node, data }">
              <span>{{ data.label }}</span>
              <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
            </template>
          </el-cascader>
        </el-form-item>
        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址" maxlength="50"/>
        </el-form-item>
        <el-form-item label="客户等级" prop="customerCategory">
          <el-select v-model="form.customerCategory" placeholder="请选择客户等级" style="width: 100%">
            <el-option
              v-for="dict in dict.type.customer_grade"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开户银行" prop="customerBank" >
          <el-input v-model="form.customerBank" placeholder="请输入客户开户银行" maxlength="20"/>
        </el-form-item>
        <el-form-item label="银行帐号" prop="customerBankAccount">
          <el-input v-model="form.customerBankAccount" placeholder="请输入客户银行卡号"
                    @input="v => form.customerBankAccount = v.replace(/[^\d]/g,'')"
                    maxlength="20"/>
        </el-form-item>
        <el-form-item label="备注信息" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入备注信息" maxlength="250"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listCustomer, getCustomer, delCustomer, addCustomer, updateCustomer} from "@/api/erp/customer";
import {regionData, CodeToText, TextToCode} from 'element-china-area-data'

export default {
  name: "Customer",
  dicts: ['customer_grade'],
  data() {
    return {

      address: '',

      options: regionData,

      selectedOptions: [],

      querySelectedOptions: [],

      addtions: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组names
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 客户管理表格数据
      customerList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        phone: null,
        customerAddress: null,
        customerCategory: null,
        customerBank: null,
        customerBankAccount: null,
        remarks: null,
        createUser: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {required: true, message: "客户名称不能为空", trigger: "blur"}
        ],
        phone: [
          {
            required: true,
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          },
        ],
      }
    };
  },

  created() {
    this.getList();
  },
  methods: {
    /*elementui选择地址*/
    handleChange(value) {
      this.selectedOptions = value
      console.log(this.selectedOptions)
      var name = ''
      this.selectedOptions.map(item =>
        name += CodeToText[item] + '') //将省市区三个拼接一起
      this.form.province = value[0];
      this.form.city = value[1];
      this.form.area = value[2];
      this.form.customerAddress = name;
    },

    handleChange1(value) {
      this.querySelectedOptions = value
      var name = ''
      this.querySelectedOptions.map(item =>
        name += CodeToText[item] + '') //将省市区三个拼接一起
      this.queryParams.customerAddress = name;
    },

    /** 查询客户管理列表 */
    getList() {
      this.loading = true;
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        phone: null,
        customerAddress: null,
        customerCategory: null,
        customerBank: null,
        customerBankAccount: null,
        remarks: null,
        createTime: null,
        updateTime: null,
        createUser: null,
        selectedOptions: null,
        detailedAddress: null,
        querySelectedOptions: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.querySelectedOptions = "";
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.selectedOptions = "";
      this.selectedOptions = ["", "", ""];
      this.reset();
      this.open = true;
      this.title = "添加客户";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      if (row.province != null && row.city != null && row.area != null) {
        this.selectedOptions = [row.province.toString(), row.city.toString(), row.area.toString()]
      }
      getCustomer(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改客户";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCustomer(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCustomer(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$modal.confirm('是否确认删除客户"' + names + '"？').then(function () {
        return delCustomer(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/customer/export', {
        ...this.queryParams
      }, `customer_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
